package ysa;

import robocode.AdvancedRobot;
import robocode.ScannedRobotEvent;

/**
 * The robot which can dodge the enemy bullets.
 */
public class DodgeBot extends AdvancedRobot {
	
	private static final int TURN_RIGHT_COEF = 30;
	private static final int TURN_RIGHT_FREE_TERM = 90;
	private static final int ENERGY_THRESHOLD = 3;
	private static final int DISTANCE_COEF = 4;
	private static final int DISTANCE_FREE_TERM = 25;
	private static final int FIRE_POWER = 2;
	
	private double previousEnergy = 100;
	private int movementDirection = 1;
	private int gunDirection = 1;

	/**
	 * The main cycle of our robot. It's behavior shold be described here.
	 */
	@Override
	public void run() {
		// simply turn the gun right while we do not see an enemy
		setTurnGunRight(Double.POSITIVE_INFINITY);
	}

	/**
	 * The event handler which works out when the enemy is in the radar scope.
	 */
	@Override
	public void onScannedRobot(ScannedRobotEvent e) {
		// stay at right angles to the opponent
		setTurnRight(e.getBearing() + TURN_RIGHT_FREE_TERM - TURN_RIGHT_COEF * movementDirection);

		// if the bot has small energy drop, assume it fired
		double changeInEnergy = previousEnergy - e.getEnergy();
		if (changeInEnergy > 0 && changeInEnergy <= ENERGY_THRESHOLD) {
			// dodge
			movementDirection = -movementDirection;
			setAhead((e.getDistance() / DISTANCE_COEF + DISTANCE_FREE_TERM) * movementDirection);
		}
		// when a bot is spotted sweep the gun and radar
		gunDirection = -gunDirection;
		setTurnGunRight(Double.POSITIVE_INFINITY * gunDirection);

		// fire directly at target
		fire(FIRE_POWER);

		// track the energy level
		previousEnergy = e.getEnergy();
	}
}